package com.luncheng.mcp.admin.controller;

import com.luncheng.mcp.core.McpClientServer;
import com.luncheng.mcp.core.enums.TransportTypeEnum;
import com.luncheng.mcp.core.model.McpClientConfig;
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.spec.McpSchema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/api/client")
public class McpClientController {
    @Autowired
    private McpClientServer mcpClientServer;

    @RequestMapping("/add")
    public List<McpSchema.ListToolsResult> add() {
        Map<String, McpSyncClient> clientMap = McpClientServer.getClientMap();
        McpSyncClient mcpSyncClient = clientMap.get("test");
        if (Objects.nonNull(mcpSyncClient)) {
            return Collections.singletonList(mcpSyncClient.listTools());
        }
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJ1c2VyUGhvbmUiOiIxMzMxMjMxMjMxMiIsInRzdG9rZW4iOiJsb2dpbl90b2tlbjoxMzY0MjkzMjc1NTY0OTAwMzUyIiwiZXhwIjoxNzQ4NDQzOTQzLCJ1c2VySWQiOiIxMzY0MjkzMjc1NTY0OTAwMzUyIiwidXNlcm5hbWUiOiLlrZnkuIAifQ.uib6bPHoc96c63KPGe3yZvo8gPUghnvOhAhcs1yOLfj7-aCTFGf6jKCkh3T6HFnjgo6we1daX0E-OHdiI3psXg");
        headers.put("Authorization-Tenant", "1364293502996840448");
        McpClientConfig clientConfig = McpClientConfig.builder()
                .transportType(TransportTypeEnum.SSE)
                .name("test")
                .serverHost("http://10.0.10.20:7860")
                .sseEndpoint("/api/v1/mcp/flow/457107556008071168/sse")
                .headers(headers)
                .requestTimeout(3600)
                .build();
        mcpClientServer.addMcpSyncServer(clientConfig);
        mcpSyncClient = clientMap.get("test");
        return Collections.singletonList(mcpSyncClient.listTools());
    }

    @RequestMapping("/exec")
    public McpSchema.CallToolResult exec() {
        Map<String, McpSyncClient> clientMap = McpClientServer.getClientMap();
        McpSyncClient mcpSyncClient = clientMap.get("test");
        if (Objects.isNull(mcpSyncClient)) {
            return null;
        }
        List<McpSchema.Tool> tools = mcpSyncClient.listTools().tools();
        Optional<McpSchema.Tool> toolOptional = tools.stream().findFirst();
        if (toolOptional.isPresent()) {
            Map<Object, Object> objectHashMap = new HashMap<>();
            objectHashMap.put("input_value", "你好");
            return mcpSyncClient.callTool(new McpSchema.CallToolRequest("MCP 工具测试工作流", objectHashMap.toString()));
        }
        return null;
    }
}
